package net.chenlin.dp.ids.client.servlet;

import net.chenlin.dp.ids.client.config.PassportClientConfig;
import net.chenlin.dp.ids.client.manager.AuthCheckManager;
import net.chenlin.dp.ids.common.base.BaseResult;
import net.chenlin.dp.ids.common.constant.GlobalErrorEnum;
import net.chenlin.dp.ids.common.constant.IdsConst;
import net.chenlin.dp.ids.common.constant.TicketConst;
import net.chenlin.dp.ids.common.entity.TicketValidateResultDTO;
import net.chenlin.dp.ids.common.util.CommonUtil;
import net.chenlin.dp.ids.common.util.CookieUtil;
import net.chenlin.dp.ids.common.util.JsonUtil;
import net.chenlin.dp.ids.common.util.WebUtil;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * web用户登录成功后的回调处理
 * @author zhouchenglin[yczclcn@163.com]
 */
public class WebAuthServlet extends HttpServlet {

    private PassportClientConfig clientConfig;

    private AuthCheckManager authCheckManager;

    public WebAuthServlet(PassportClientConfig clientConfig, AuthCheckManager authCheckManager) {
        this.clientConfig = clientConfig;
        this.authCheckManager = authCheckManager;
    }

    /**
     * get请求
     * @param req
     * @param resp
     * @throws IOException
     */
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String ticket = req.getParameter(IdsConst.TICKET_KEY);
        String targetUrl = req.getParameter(IdsConst.TARGET_KEY);
        // 校验ticket为空，直接返回错误
        if (CommonUtil.strIsEmpty(ticket)) {
            BaseResult bizError = GlobalErrorEnum.BizError.getResult();
            WebUtil.write(resp, JsonUtil.toStr(bizError));
            return;
        }
        // 目标地址为空，则默认为系统首页
        if (CommonUtil.strIsEmpty(targetUrl)) {
            targetUrl = clientConfig.getServerName();
        }

        // 是否为authStatus回调，表示服务端未登录
        if (ticket.startsWith(TicketConst.AUTH_STATUS_NOT_LOGIN_PREFIX)) {
            CookieUtil.remove(req, resp, clientConfig.getAuthIdCookieName(), clientConfig.getCookieDomain());
            String authStatusUrl = WebUtil.requestAppendParam(targetUrl, new String[]{"idsLogin"}, new Object[]{"false"});
            resp.sendRedirect(resp.encodeRedirectURL(authStatusUrl));
            return;
        }

        // 校验ticket合法性
        TicketValidateResultDTO validateResultDTO = authCheckManager.validateTicket(ticket);
        if (validateResultDTO == null) {
            // 跳转登录页
            CookieUtil.remove(req, resp, clientConfig.getAuthIdCookieName(), clientConfig.getCookieDomain());
            resp.sendRedirect(resp.encodeRedirectURL(clientConfig.getServLogoutUrl(targetUrl)));
        } else {
            // 跳转目标页
            CookieUtil.set(resp, clientConfig.getAuthIdCookieName(), validateResultDTO.getSessionId(),
                    clientConfig.getCookieDomain(), validateResultDTO.getRememberMe());
            resp.sendRedirect(resp.encodeRedirectURL(targetUrl));
        }

    }

    /**
     * post请求
     * @param req
     * @param resp
     */
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        this.doGet(req, resp);
    }

}
